#include "widget.h"
#include "ui_widget.h"
#include <QVBoxLayout>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
    , textEdit(new QTextEdit(this))
    , testConnectionButton(new QPushButton(tr("连接"), this))
    , socket(new QTcpSocket(this))
    , sendButton(new QPushButton(tr("发送"), this))
{
    ui->setupUi(this);
    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(textEdit);
    layout->addWidget(testConnectionButton);
    layout->addWidget(sendButton);

    connect(testConnectionButton, &QPushButton::clicked,this, &Widget::onTestConnectionButton);
    connect(socket, &QTcpSocket::readyRead, this, &Widget::onSocketReadyRead);
    connect(sendButton, &QPushButton::clicked, this, &Widget::onTestSendButton);
    connect(socket, QOverload<QAbstractSocket::SocketError>::of(&QAbstractSocket::error), this, &Widget::onSocketErrorOccurred);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::onTestConnectionButton()
{
    QString message = "Hello, Server!"; // 要发送的消息
    socket->abort(); // 重置socket状态
    socket->connectToHost("192.168.1.45", 8080); // 假设后端服务器在本机的12345端口监听

    connect(socket, &QTcpSocket::connected, [this, message]()
    {
        textEdit->clear();
        socket->write(message.toUtf8());
    });

       // 等待一定时间来检查连接状态
    socket->waitForConnected(3000);
}

void Widget::onSocketReadyRead()
{
    QByteArray data = socket->readAll();
    textEdit->append("Received from server: " + QString(data));
}

void Widget::onSocketErrorOccurred()
{
    textEdit->append("Socket error: " + socket->errorString());
    socket->deleteLater();
}

void Widget::onTestSendButton()
{
    QString message = textEdit->toPlainText();
    socket->write(message.toUtf8());
}

